<template>
	<div id="user-profile-view">
		<div class="profile-container">
			<a-card title="个人信息" :loading="loading">
				<a-form
					:model="userForm"
					name="userProfile"
					:label-col="{ span: 6 }"
					:wrapper-col="{ span: 18 }"
					@finish="handleUpdateProfile"
				>
					<a-form-item label="用户头像">
						<AvatarUpload v-model="userForm.userAvatar" :placeholder="userForm.userName" :size="80" />
					</a-form-item>

					<a-form-item label="用户名" name="userName" :rules="[{ required: true, message: '请输入用户名!' }]">
						<a-input v-model:value="userForm.userName" placeholder="请输入用户名" />
					</a-form-item>

					<a-form-item label="用户账号">
						<a-input v-model:value="userForm.userAccount" disabled />
					</a-form-item>

					<a-form-item label="用户角色">
						<div style="display: flex; align-items: center">
							<a-tag :color="getRoleColor(userForm.userRole)">
								{{ getRoleText(userForm.userRole) }}
							</a-tag>
						</div>
					</a-form-item>

					<a-form-item label="用户简介" name="userProfile">
						<a-textarea
							v-model:value="userForm.userProfile"
							placeholder="请输入个人简介"
							:rows="4"
							:max-length="200"
							show-count
						/>
					</a-form-item>

					<a-form-item label="注册时间">
						<span>{{ formatTime(userForm.createTime) }}</span>
					</a-form-item>

					<a-form-item :wrapper-col="{ offset: 6, span: 18 }">
						<a-space>
							<a-button type="primary" html-type="submit" :loading="updating"> 保存修改 </a-button>
							<a-button @click="resetForm"> 重置 </a-button>
						</a-space>
					</a-form-item>
				</a-form>
			</a-card>

			<!-- 修改密码卡片 -->
			<a-card title="修改密码" style="margin-top: 24px">
				<a-alert
					message="安全提示"
					description="为了您的账户安全，请设置密码长度为8-20位。新密码不能与当前密码相同。"
					type="info"
					show-icon
					style="margin-bottom: 24px"
				/>
				<a-form
					:model="passwordForm"
					name="passwordForm"
					:label-col="{ span: 6 }"
					:wrapper-col="{ span: 18 }"
					@finish="handleUpdatePassword"
				>
					<a-form-item label="当前密码" name="oldPassword" :rules="[{ required: true, message: '请输入当前密码!' }]">
						<a-input-password
							v-model:value="passwordForm.oldPassword"
							placeholder="请输入当前密码"
							autocomplete="current-password"
						/>
					</a-form-item>

					<a-form-item
						label="新密码"
						name="newPassword"
						:rules="[
							{ required: true, message: '请输入新密码!' },
							{ min: 8, message: '密码长度不能少于8位!' },
							{ max: 20, message: '密码长度不能超过20位!' },
							{ validator: validatePasswordStrength },
						]"
					>
						<a-input-password
							v-model:value="passwordForm.newPassword"
							placeholder="请输入新密码（8-20位）"
							autocomplete="new-password"
						/>
					</a-form-item>

					<a-form-item
						label="确认新密码"
						name="confirmPassword"
						:rules="[{ required: true, message: '请确认新密码!' }, { validator: validateConfirmPassword }]"
					>
						<a-input-password
							v-model:value="passwordForm.confirmPassword"
							placeholder="请再次输入新密码"
							autocomplete="new-password"
						/>
					</a-form-item>

					<a-form-item :wrapper-col="{ offset: 6, span: 18 }">
						<a-space>
							<a-button type="primary" html-type="submit" :loading="passwordUpdating"> 修改密码 </a-button>
							<a-button @click="resetPasswordForm"> 重置 </a-button>
						</a-space>
					</a-form-item>
				</a-form>
			</a-card>
		</div>
	</div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { message } from 'ant-design-vue'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { getLoginUser, updateUser, updateUserPassword } from '@/api/userController'
import ACCESS_ENUM from '@/access/accessEnum'
import dayjs from 'dayjs'
import { AvatarUpload } from '@/components/common'

const loginUserStore = useLoginUserStore()
const loading = ref(false)
const updating = ref(false)
const passwordUpdating = ref(false)

// 用户表单数据
const userForm = reactive<{
	id?: number
	userName?: string
	userAccount?: string
	userAvatar?: string
	userProfile?: string
	userRole?: string
	createTime?: string
	vipExpireTime?: string
}>({})

// 密码表单数据
const passwordForm = reactive<{
	oldPassword?: string
	newPassword?: string
	confirmPassword?: string
}>({
	oldPassword: '',
	newPassword: '',
	confirmPassword: '',
})

// 获取角色颜色
const getRoleColor = (role?: string) => {
	const colorMap: Record<string, string> = {
		[ACCESS_ENUM.NOT_LOGIN]: 'default',
		[ACCESS_ENUM.USER]: 'blue',
		vip: 'gold',
		[ACCESS_ENUM.ADMIN]: 'red',
	}
	return colorMap[role || ACCESS_ENUM.NOT_LOGIN]
}

// 获取角色文本
const getRoleText = (role?: string) => {
	const textMap: Record<string, string> = {
		[ACCESS_ENUM.NOT_LOGIN]: '未登录',
		[ACCESS_ENUM.USER]: '普通用户',
		vip: 'VIP用户',
		[ACCESS_ENUM.ADMIN]: '管理员',
	}
	return textMap[role || ACCESS_ENUM.NOT_LOGIN]
}

// 格式化时间
const formatTime = (time?: string) => {
	return time ? dayjs(time).format('YYYY-MM-DD HH:mm:ss') : '-'
}

// 获取用户信息
const fetchUserProfile = async () => {
	loading.value = true
	try {
		const res = await getLoginUser()
		if (res.data.code === 0 && res.data.data) {
			Object.assign(userForm, res.data.data)
		}
	} catch (error) {
		message.error('获取用户信息失败')
	} finally {
		loading.value = false
	}
}

// 更新用户信息
const handleUpdateProfile = async () => {
	updating.value = true
	try {
		const res = await updateUser({
			id: userForm.id,
			userName: userForm.userName,
			userAvatar: userForm.userAvatar,
			userProfile: userForm.userProfile,
		})
		if (res.data.code === 0) {
			message.success('更新成功')
			// 更新全局用户信息
			await loginUserStore.fetchLoginUser()
		} else {
			message.error(res.data.message || '更新失败')
		}
	} catch (error) {
		message.error('更新失败')
	} finally {
		updating.value = false
	}
}

// 重置表单
const resetForm = () => {
	fetchUserProfile()
}

// 头像上传前检查
const beforeUpload = (file: File) => {
	const isJpgOrPng = file.type === 'image/jpeg' || file.type === 'image/png'
	if (!isJpgOrPng) {
		message.error('只能上传 JPG/PNG 格式的图片!')
		return false
	}
	return true
}

// 验证确认密码
const validateConfirmPassword = async (_rule: any, value: string) => {
	if (value && value !== passwordForm.newPassword) {
		return Promise.reject(new Error('两次输入的密码不一致！'))
	}
	return Promise.resolve()
}

// 验证新密码强度
const validatePasswordStrength = async (_rule: any, value: string) => {
	if (!value) {
		return Promise.resolve()
	}

	// 检查是否与当前密码相同
	if (value === passwordForm.oldPassword) {
		return Promise.reject(new Error('新密码不能与当前密码相同！'))
	}

	return Promise.resolve()
}

// 重置密码表单
const resetPasswordForm = () => {
	passwordForm.oldPassword = ''
	passwordForm.newPassword = ''
	passwordForm.confirmPassword = ''
}

// 处理修改密码
const handleUpdatePassword = async () => {
	passwordUpdating.value = true
	try {
		const res = await updateUserPassword({
			oldPassword: passwordForm.oldPassword,
			newPassword: passwordForm.newPassword,
		})

		if (res.data.code === 0) {
			message.success('密码修改成功！为了账户安全，建议您重新登录')
			resetPasswordForm()

			setTimeout(() => {
				loginUserStore.setLoginUser({})
				window.location.href = '/user/login'
			}, 2000)
		} else {
			message.error(res.data.message || '密码修改失败')
		}
	} catch (error: any) {
		console.error('密码修改失败', error)
		// 根据错误信息给出更友好的提示
		if (error.response?.status === 400) {
			message.error('当前密码输入错误，请检查后重试')
		} else {
			message.error('密码修改失败，请重试')
		}
	} finally {
		passwordUpdating.value = false
	}
}

onMounted(() => {
	fetchUserProfile()
})
</script>

<style scoped lang="scss">
#user-profile-view {
	max-width: 800px;
	margin: 0 auto;
	padding: 24px;

	.profile-container {
		// 限制头像上传组件的最大宽度，防止超宽显示
		:deep(.avatar-upload) {
			max-width: 500px; // 设置最大宽度
			width: 100%;
			
			.avatar-actions {
				max-width: 400px; // 限制操作区域宽度
				width: 100%;
			}
		}

		.avatar-upload {
			display: flex;
			align-items: center;
			margin-bottom: 8px;

			.avatar-container {
				position: relative;
				display: inline-block;

				.avatar-loading {
					position: absolute;
					top: 0;
					left: 0;
					right: 0;
					bottom: 0;
					background: rgba(255, 255, 255, 0.8);
					display: flex;
					align-items: center;
					justify-content: center;
					border-radius: 50%;
				}
			}
		}

		.avatar-tips {
			margin-top: 4px;
		}

		// 修改密码卡片样式
		.ant-card:last-child {
			border: 1px solid #f0f0f0;

			:deep(.ant-card-head) {
				background: #fafafa;

				.ant-card-head-title {
					color: #595959;
					font-weight: 500;
				}
			}
		}
	}
}
</style>
